package com.win.controller.sqoop;

import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class SqoopExecutor {
    private String hostname;
    private String username;
    private String password;

    public SqoopExecutor(String hostname, String username, String password) {
        this.hostname = hostname;
        this.username = username;
        this.password = password;
    }

    public SqoopResult execute(SqoopCommand command) throws IOException, JSchException {
        Session session = null;
        try {
            JSch jsch = new JSch();//Java Secure Channel的缩写，是一个用于实现SSH协议的纯Java类库
            session = jsch.getSession(username, hostname, 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            //使用JSch库打开一个 "exec" 类型的 SSH Channel，可以在指定会话(session)上执行命令。
            Channel channel = session.openChannel("exec");
            //将一个待执行的命令设置进了 SSH Channel 中，以便在远程服务器上执行该命令
            ((ChannelExec)channel).setCommand("export PATH=/training/sqoop-1.4.6.bin__hadoop-2.0.4-alpha/bin:$PATH;"+command.toString());
            channel.setInputStream(null);
            //将此 SSH Channel 的输入流设置为 null，即不接收任何输入。由于该 SSH Channel 类型为 "exec"，通常用于执行远程命令，并不需要从输入流中读取任何数据。

           //获取 SSH Channel 的标准输出流和错误输出流，并建立与远程服务器的连接
            InputStream stdout = channel.getInputStream();
            InputStream stderr = ((ChannelExec) channel).getErrStream();
            channel.connect();

            String output = readStream(stdout);
            String error = readStream(stderr);

            int exitStatus = channel.getExitStatus();

            return new SqoopResult(output, error, exitStatus);
        } finally {
            if (session != null) {
                session.disconnect();
            }
        }
    }
    //读取通过 SSH Channel 执行命令所获得的标准输出流和错误输出流，并将它们转换成字符串类型以便于后续的处理和分析。
    private String readStream(InputStream stream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line).append("\n");
        }
        return result.toString().trim();
    }

    public boolean testConnection() {
        Session session = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, hostname, 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            return true;
        } catch (JSchException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }

}

